// 配置管理工具
class ConfigManager {
  constructor() {
    this.config = null;
    this.loadPromise = null;
  }

  // 加载配置文件
  async loadConfig() {
    if (this.config) {
      return this.config;
    }

    if (this.loadPromise) {
      return this.loadPromise;
    }

    this.loadPromise = this._fetchConfig();
    this.config = await this.loadPromise;
    return this.config;
  }

  // 获取配置
  async _fetchConfig() {
    try {
      const response = await fetch('/config.json');
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const config = await response.json();
      console.log('配置加载成功:', config);
      return config;
    } catch (error) {
      console.error('配置加载失败，使用默认配置:', error);
      // 返回默认配置
      return {
        ossBaseUrl: "https://poster-oss.oss-cn-shenzhen.aliyuncs.com",
        apiBaseUrl: "https://hpsq.doctopia.com.cn"
      };
    }
  }

  // 获取OSS基础URL
  async getOssBaseUrl() {
    const config = await this.loadConfig();
    return config.ossBaseUrl;
  }

  // 获取API基础URL
  async getApiBaseUrl() {
    const config = await this.loadConfig();
    return config.apiBaseUrl;
  }

  // 构建完整的OSS URL
  async buildOssUrl(path) {
    const baseUrl = await this.getOssBaseUrl();
    return `${baseUrl}${path.startsWith('/') ? path : '/' + path}`;
  }

  // 构建完整的API URL
  async buildApiUrl(path) {
    const baseUrl = await this.getApiBaseUrl();
    return `${baseUrl}${path.startsWith('/') ? path : '/' + path}`;
  }
}

// 创建单例实例
const configManager = new ConfigManager();

export default configManager;
